"""
Create Prompt Models Management Command
创建提示词模型管理命令
"""
from django.core.management.base import BaseCommand
from django.apps import apps
from django.db import connection

class Command(BaseCommand):
    help = '创建提示词管理相关的数据表'

    def handle(self, *args, **options):
        try:
            from apps.ai_integration.models_prompt import (
                CustomPromptTemplate,
                PromptUsageLog,
                PromptTemplateVersion,
                PromptTemplateReview
            )

            self.stdout.write(self.style.SUCCESS('开始创建提示词管理数据表...'))

            # 检查表是否已存在
            tables_to_create = [
                'ai_prompt_templates',
                'ai_prompt_usage_logs',
                'ai_prompt_template_versions',
                'ai_prompt_template_reviews'
            ]

            with connection.cursor() as cursor:
                for table_name in tables_to_create:
                    cursor.execute("""
                        SELECT COUNT(*) FROM information_schema.tables
                        WHERE table_name = %s
                    """, [table_name])

                    if cursor.fetchone()[0] == 0:
                        self.stdout.write(f'创建表: {table_name}')
                    else:
                        self.stdout.write(f'表已存在: {table_name}')

            self.stdout.write(self.style.SUCCESS('提示词管理数据表检查完成！'))

        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'创建提示词管理数据表失败: {str(e)}')
            )